package com.gz.mylife.app;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.App;
import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.SelectListAdapter;
import com.gz.mylife.adapter.SelectListAdapter.OnItemClickListener;
import com.gz.mylife.po.ChoosePhotoInfo;
import com.gz.mylife.util.DateTimePickDialogUtil;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.gz.mylife.widget.OfflineDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.concurrent.ThreadExecutor;
import com.zl.smartmall.library.listener.MaintenancesProjectListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.listener.SubmitMaintenacesListener;
import com.zl.smartmall.library.listener.UploadEquimentPictureListener;
import com.zl.smartmall.library.po.MaintenacesInfos;
import com.zl.smartmall.library.po.MaintenancesProject;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

public class ApplyEquimentActivity extends BaseActivity implements OnClickListener, OnTouchListener, OnLoadingCoverRefreshListener, OnItemClickListener, OnDismissListener {
	private static final String TAG = ApplyEquimentActivity.class.getSimpleName();
	private int date1_id;// 时间控件1的ID
	private int date2_id;// 时间控件2的ID
	private EditText starttime;// 开始时间
	private EditText endtime;// 结束时间
	private EditText et_receiver;// 联系人
	private EditText et_receiver_phone;// 联系电话
	private EditText et_equiment_address;// 报修地点
	private EditText et_reason;//报修详情
	private TextView spinner;
	//private ArrayAdapter<String> arr_adapter;
	private List<MaintenancesProject> maintenancesProject;
	private Button btn_submit;//提交按钮
	private Dialog mMenudialog;
	private TextView mTvTitle;
	private Dialog mLoadingData;
	private Button btn_change;//确认按钮
	private SubmitMaintenacesListener submitMaintenacesListener;
	private static UploadEquimentPictureListener uploadEquimentPicListener;
	private OfflineDialog mOfflineDialog;
	private LayoutInflater mInflater;
	private String address;
	private LoadingCover mLoadingCover;
	SimpleDateFormat sdf;
	Date start;
	Date end;
	private String mallcomid;
	private String mImgTempCachePath;
	private String mImgCapturePath;

	private static List<ChoosePhotoInfo> imgsinfo;
	private ContentResolver mContentResolver;
	private DisplayImageOptions mImageOptions;
	private View mRootView;
	private String filename;
	private MyHandler mHandler;//开启线程上传图片
	private String[] paramimg = new String[4];//图片数组
	private GridView pictures_gridview;
	private MyAdapter adapter;//图片适配器

	private Boolean islongclick=false;
	private PopupWindow mSelectWindow;
	private SelectListAdapter repairadapter;//报修项目下拉适配器
	private int option_value = 0;//报修项目标识值
	private int com_id = 0;//报修项目最高组织机构ID
	private int root_id = 0;//报修项目组织机构ID
	private String option_name = "";//报修项目名称
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mRootView = getLayoutInflater().inflate(R.layout.activity_equipment, null);
		setContentView(mRootView);
		setActionbarTitle("维修申报", false);
		Bundle bundle = this.getIntent().getExtras();
		String name = bundle.getString("name");
		String newname ;
		if(name.length()>0){
			newname = name.substring(0,name.length()-(name.substring(1)).length())+" * *"+name.substring(name.length());
		}else{
			newname = "";
		}


		String phone = bundle.getString("phone");
		address = bundle.getString("address");
		mallcomid = bundle.getString("mallcomid");
		mInflater = getLayoutInflater();

		mLoadingData = new Dialog(this, R.style.DialogTheme);
		mLoadingData.setContentView(R.layout.loading_data_dialog2);
		mLoadingData.setCancelable(false);
		mLoadingData.setCanceledOnTouchOutside(false);

		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mHandler = new MyHandler(this);
		btn_submit = (Button) findViewById(R.id.btn_submit);
		btn_submit.setOnClickListener(this);
		starttime = (EditText) findViewById(R.id.start_time);
		endtime = (EditText) findViewById(R.id.end_time);
		et_receiver = (EditText) findViewById(R.id.et_receiver);
		et_equiment_address = (EditText) findViewById(R.id.et_equiment_address);
		et_receiver_phone = (EditText) findViewById(R.id.et_receiver_phone);
		et_reason = (EditText)findViewById(R.id.et_reason);
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		starttime.setText(sdf.format(new Date().getTime()));
		endtime.setText(sdf.format(new Date().getTime()));
		date1_id = starttime.getId();
		date2_id = endtime.getId();
		starttime.setOnTouchListener(this);
		endtime.setOnTouchListener(this);
		spinner = (TextView) findViewById(R.id.et_equiment_project);
		spinner.setOnClickListener(this);
		et_receiver.setText(newname);
		et_receiver_phone.setText(phone);
		et_equiment_address.setText(address);
		mContentResolver = getContentResolver();
		mImgCapturePath = mImgTempCachePath = Tools.obtainDirPath(getApplicationContext(), Constants.FOLDER_IMG_TEMP_CACHE);
		App.mChoosePhotoInfoQueue = new SparseArray<ChoosePhotoInfo>();
		imgsinfo = new ArrayList<ChoosePhotoInfo>();//存放图片信息
		imgsinfo.clear();
		pictures_gridview = (GridView)findViewById(R.id.pictures_gridview);
		adapter = new MyAdapter();
		pictures_gridview.setAdapter(adapter);
		findViewById(R.id.btn_pic_from_camera).setOnClickListener(this);
		findViewById(R.id.btn_pic_from_album).setOnClickListener(this);
		initListener();
		onLoadingEquiment();//加载维修项目
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_submit:          //点击提交订单的按钮

			try {
				start = sdf.parse(starttime.getText().toString().trim());
				end = sdf.parse(endtime.getText().toString().trim());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if ("".equals(et_receiver.getText().toString().trim())) {
				Toast.makeText(ApplyEquimentActivity.this, "请输入联系人", Toast.LENGTH_LONG).show();
			}else if ("".equals(et_receiver_phone.getText().toString().trim())) {
				Toast.makeText(ApplyEquimentActivity.this, "请输入联系方式", Toast.LENGTH_LONG).show();
			}else if ("".equals(et_equiment_address.getText().toString().trim())){
				Toast.makeText(ApplyEquimentActivity.this, "请输入维修地址", Toast.LENGTH_LONG).show();
			}else if ("".equals(et_reason.getText().toString().trim())) {
				Toast.makeText(ApplyEquimentActivity.this, "请输入维修详情", Toast.LENGTH_LONG).show();
			}else if (start.getTime()>end.getTime()) {
				Toast.makeText(ApplyEquimentActivity.this, "请正确输入预约时间", Toast.LENGTH_LONG).show();
			}else {
				createDialog();
			}
			break;
		case R.id.btn_pic_from_album://选择图片
			intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_ALBUM);
			break;

		case R.id.btn_pic_from_camera://选择照相机
			App.time = System.currentTimeMillis()+"";
			filename = "/capture-"+App.time+".jpg";
			App.img_name = filename;
			mImgCapturePath = mImgTempCachePath + "/capture-" +App.time+ ".jpg";
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra("scale", true);
			intent.putExtra("noFaceDetection", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(mImgCapturePath)));
			startActivityForResult(intent, Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA);
			break;
		case R.id.et_equiment_project:
			showAccountChoiceWindow();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

		}
		return super.onKeyDown(keyCode, event);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Define.ACTIVITY_CODE_PICTURE_FROM_ALBUM://选择本地图片
			handlePictureFromAlbum(resultCode, data);
			adapter.notifyDataSetChanged();
			break;

		case Define.ACTIVITY_CODE_PICTURE_FROM_CAMERA://拍照
			handlePictureFromCamera(resultCode, data);
			adapter.notifyDataSetChanged();
			break;
		case 2:

			break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

			if (v.getId() == date1_id) {
				DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
						ApplyEquimentActivity.this, starttime.getText().toString());
				dateTimePicKDialog.dateTimePicKDialog(starttime);
			} else if (v.getId() == date2_id) {
				DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
						ApplyEquimentActivity.this, endtime.getText().toString());
				dateTimePicKDialog.dateTimePicKDialog(endtime);
			}

		}
		return true;
	}

	public void onLoadingEquiment() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getMaintenacesProject(mallcomid,address,buildListener(RequestCode.PULL));
	}
	private MaintenancesProjectListener buildListener(RequestCode requestCode) {
		return new MaintenancesProjectListener(requestCode) {

			@Override
			public void onResponseFailed() {
				mLoadingCover.onRefreshFailed();
			}

			@Override
			public void onOffline() {
				//您已处于离线状态
				Toast.makeText(ApplyEquimentActivity.this, Define.MSG_OFFLINE_ERROR, Toast.LENGTH_LONG).show();
			}

			@Override
			public void onNoNetWork() {
				//无网络连接
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
				Toast.makeText(ApplyEquimentActivity.this, Define.MSG_NO_NETWORK, Toast.LENGTH_LONG).show();
			}

			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NO_MORE_DATA);
			}

			@Override
			public void onResponseSuccess(List<MaintenancesProject> maintenancesProjects) {
				// TODO Auto-generated method stub
				if(getRequestCode() == RequestCode.PULL) {
					maintenancesProject = new ArrayList<MaintenancesProject>();
					maintenancesProject.clear();
				}
				maintenancesProject.addAll(maintenancesProjects);
				if (maintenancesProjects.size()>0) {
					spinner.setText(maintenancesProjects.get(0).getOptionname());
					option_value = maintenancesProjects.get(0).getOptionvalue();
					option_name = maintenancesProjects.get(0).getOptionname();
					com_id = maintenancesProjects.get(0).getCom_id();
					root_id = maintenancesProjects.get(0).getRoot_id();
				}
				mLoadingCover.onRefreshSuccess();
			}
		};
	}


	private void initListener() {

		submitMaintenacesListener = new SubmitMaintenacesListener() {

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "订单提交失败, 请重试", Toast.LENGTH_SHORT);
				mLoadingData.dismiss();
			}

			@Override
			public void onOffline() {//处于离线状态
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingData.dismiss();
			}

			@Override
			public void onNoNetWork() {//没有任何网络连接
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
				mLoadingData.dismiss();
			}
			@Override
			public void onResponseFail(String msg) {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), msg);
				mLoadingData.dismiss();
			}

			@Override
			public void onResponseSuccess(String orderCode) {
				// TODO Auto-generated method stub
				ThreadExecutor.getInstance().execute(new Runnable() {
					@Override
					public void run() {
						Message msg = mHandler.obtainMessage(1);
						mHandler.sendMessage(msg);
					}
				});
				Intent intent = new Intent();
				intent.putExtra("address", address);
				intent.putExtra("mallcomid", mallcomid);
				intent.setClass(getApplicationContext(), MyEquipments.class);
				startActivity(intent);
				finish();
				mLoadingData.dismiss();
			}
		};
		uploadEquimentPicListener = new UploadEquimentPictureListener() {
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "图片上传失败, 请重试", Toast.LENGTH_SHORT);
				mLoadingData.dismiss();
			}

			@Override
			public void onOffline() {//处于离线状态
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingData.dismiss();
			}

			@Override
			public void onNoNetWork() {//没有任何网络连接
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
				mLoadingData.dismiss();

			}
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				mLoadingData.dismiss();
			}
		};
	}
	//点击提交是维修申报的弹框确认
	private void createDialog() {
		mMenudialog = new Dialog(this, R.style.DialogTheme);
		View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.mycommunity_dialog_layout, null);
		mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
		mTvTitle.setText("确认提交申报");
		btn_change = (Button) dialogView.findViewById(R.id.btn_change);
		btn_change.setText("确认");
		btn_change.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLoadingData.show();
				submitMaininfo();//点击确认调用提交维修信息的方法
				mMenudialog.dismiss();

			}
		});
		dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mMenudialog.dismiss();
			}
		});
		mMenudialog.setContentView(dialogView);
		mMenudialog.setCancelable(false);
		mMenudialog.setCanceledOnTouchOutside(false);
		mMenudialog.show();
	}

	//提交申报的方法
	private void submitMaininfo() {
		MaintenacesInfos maininfos = new MaintenacesInfos();
		maininfos.setAddress(et_equiment_address.getText().toString().trim());
		maininfos.setApplyname(et_receiver.getText().toString().trim());
		maininfos.setApplytype(3);
		maininfos.setAppointmentat(starttime.getText().toString().trim());
		maininfos.setAppointmentatend(endtime.getText().toString().trim());
		maininfos.setInfo(et_reason.getText().toString().trim());
		maininfos.setRepairitem(option_name);
		maininfos.setTelephone(et_receiver_phone.getText().toString().trim());
		maininfos.setAddcode(address);
		for (int i = 0; i < imgsinfo.size(); i++) {
			paramimg[i] = imgsinfo.get(i).getUrl();
		}
		ISmartMall.getInstance().addMaintenaces(mallcomid,FragmentPersonal.mUserInfo.getUid()+"",maininfos,paramimg[0],paramimg[1],paramimg[2],paramimg[3],option_value,com_id,root_id,submitMaintenacesListener);

	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub

	}
	private void thumbnailClickEvent(int item) {//选好图片之后，点击图片预览大图
		if(App.mChoosePhotoInfoQueue.get(item) != null) {
			ArrayList<String> url = new ArrayList<String>();
			for(int i = 0; i < App.mChoosePhotoInfoQueue.size(); i++) {
				int key = App.mChoosePhotoInfoQueue.keyAt(i);
				url.add(App.mChoosePhotoInfoQueue.get(key).getFilepath());
			}
			Intent intent = new Intent(getApplicationContext(), HDPictureBrowse.class);
			intent.putStringArrayListExtra("picture", url);
			intent.putExtra("position", item);
			startActivity(intent);
		}
	}
	private void handlePictureFromAlbum(int resultCode, Intent data) {//选择本地图片
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if(imgsinfo.size() >= 4) {
				ToastUtils.showToast(this, "亲 , 最多上传4张图片");
				return;
			}
			try {
				Uri uri = data.getData();
				String column_index = getPathByUri4kitkat(getApplicationContext(),uri);
				String photoPath = null;
				//最后根据索引值获取图片路径
				photoPath = column_index;
				photoPath = mImgTempCachePath + photoPath.substring(photoPath.lastIndexOf("/"));
				filename = photoPath.substring(photoPath.lastIndexOf("/")+1);
				photoPath = Tools.saveBitmapAndGetPath(this,
						photoPath, uri);
				try {
					InputStream inputStream = new FileInputStream(new File(photoPath));
					byte[] bytes = readInputStream(inputStream);
					String string = com.loopj.android.http.Base64.encodeToString(bytes, com.loopj.android.http.Base64.DEFAULT);

					ChoosePhotoInfo info = new ChoosePhotoInfo();
					info.setPath(string);
					info.setUrl(filename);
					info.setFilepath("file://" + photoPath);
					info.setBendipath(photoPath);
					imgsinfo.add(info);
					App.mChoosePhotoInfoQueue.put(App.mChoosePhotoInfoQueue.size(), info);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (OutOfMemoryError e) {
				CrashHandler.e(e);

			} 
		}

	}

	private void handlePictureFromCamera(int resultCode, Intent data) {
		if(resultCode == RESULT_OK) {
			if(imgsinfo.size() >= 4) {
				ToastUtils.showToast(this, "亲 , 最多上传4张图片");
				return;
			}
			mImgCapturePath = mImgTempCachePath + "/capture-" +App.time+ ".jpg";
			mImgCapturePath = Tools.saveBitmapAndGetPath(this, mImgCapturePath);

			try {
				InputStream inputStream = new FileInputStream(new File(mImgCapturePath));
				byte[] bytes = readInputStream(inputStream);
				String string = com.loopj.android.http.Base64.encodeToString(bytes, com.loopj.android.http.Base64.DEFAULT);
				ChoosePhotoInfo info = new ChoosePhotoInfo();
				info.setPath(string);
				info.setUrl(et_receiver_phone.getText().toString().trim()+mImgCapturePath.substring(mImgCapturePath.lastIndexOf("/")+1));
				info.setBendipath(mImgCapturePath);
				info.setFilepath("file://" + mImgCapturePath);
				imgsinfo.add(info);
				App.mChoosePhotoInfoQueue.put(App.mChoosePhotoInfoQueue.size(), info);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
	private static byte[] readInputStream(InputStream inputStream)throws IOException {
		byte[] buffer = new byte[4096];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
	//开启线程上传图片
	private static class MyHandler extends Handler {

		private ApplyEquimentActivity mOuter;

		public MyHandler(ApplyEquimentActivity outer) {
			mOuter = outer;
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mOuter == null) {
				return;
			}
			switch (msg.what) {
			case 1:
				for (int i = 0; i < imgsinfo.size(); i++) {
					//循环上传图片
					ISmartMall.getInstance().uploadEquimentPicture(imgsinfo.get(i).getPath(),imgsinfo.get(i).getUrl(),uploadEquimentPicListener);
				}
				break;
			}
		};

		public void release() {
			new WeakReference<ApplyEquimentActivity>(mOuter);
		}
	}


	@SuppressLint("NewApi")  
	public static String getPathByUri4kitkat(final Context context, final Uri uri) {  
		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  
		// DocumentProvider  
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  
			if (isExternalStorageDocument(uri)) {// ExternalStorageProvider  
				final String docId = DocumentsContract.getDocumentId(uri);  
				final String[] split = docId.split(":");  
				final String type = split[0];  
				if ("primary".equalsIgnoreCase(type)) {  
					return Environment.getExternalStorageDirectory() + "/" + split[1];  
				}  
			} else if (isDownloadsDocument(uri)) {// DownloadsProvider  
				final String id = DocumentsContract.getDocumentId(uri);  
				final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),  
						Long.valueOf(id));  
				return getDataColumn(context, contentUri, null, null);  
			} else if (isMediaDocument(uri)) {// MediaProvider  
				final String docId = DocumentsContract.getDocumentId(uri);  
				final String[] split = docId.split(":");  
				final String type = split[0];  
				Uri contentUri = null;  
				if ("image".equals(type)) {  
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
				} else if ("video".equals(type)) {  
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
				} else if ("audio".equals(type)) {  
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
				}  
				final String selection = "_id=?";  
				final String[] selectionArgs = new String[] { split[1] };  
				return getDataColumn(context, contentUri, selection, selectionArgs);  
			}  
		} else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore  
			return getDataColumn(context, uri, null, null);  
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {// File  
			return uri.getPath();  
		}  
		return null;  
	}  

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {  
		Cursor cursor = null;  
		final String column = "_data";  
		final String[] projection = { column };  
		try {  
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);  
			if (cursor != null && cursor.moveToFirst()) {  
				final int column_index = cursor.getColumnIndexOrThrow(column);  
				return cursor.getString(column_index);  
			}  
		} finally {  
			if (cursor != null)  
				cursor.close();  
		}  
		return null;  
	}  

	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is ExternalStorageProvider. 
	 */  
	public static boolean isExternalStorageDocument(Uri uri) {  
		return "com.android.externalstorage.documents".equals(uri.getAuthority());  
	}  

	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is DownloadsProvider. 
	 */  
	public static boolean isDownloadsDocument(Uri uri) {  
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
	}  

	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is MediaProvider. 
	 */  
	public static boolean isMediaDocument(Uri uri) {  
		return "com.android.providers.media.documents".equals(uri.getAuthority());  
	}  
	private class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return imgsinfo.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return imgsinfo.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			View v = View.inflate(ApplyEquimentActivity.this, R.layout.activity_gridviewimage, null);
			ImageView imageview = (ImageView) v.findViewById(R.id.ItemImage);
			final TextView delete = (TextView) v.findViewById(R.id.delete);

			ImageLoader.getInstance().displayImage(imgsinfo.get(position).getFilepath(), imageview,mImageOptions);


			/*imageview.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					islongclick=true;
					delete.setVisibility(View.VISIBLE);
					return false;
				}
			});*/
			delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					createDialogdelete(position);
				}
			});

			imageview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(!islongclick){
						thumbnailClickEvent(position);
					}
					islongclick=false;
				}
			});

			return v;
		}
	} 
	private void createDialogdelete(final int position) {
		mMenudialog = new Dialog(this, R.style.DialogTheme);
		View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.mycommunity_dialog_layout, null);
		mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
		mTvTitle.setText("确定要删除吗？");
		btn_change = (Button) dialogView.findViewById(R.id.btn_change);
		btn_change.setText("确定");
		btn_change.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				imgsinfo.remove(position);
				App.mChoosePhotoInfoQueue.removeAt(position);
				adapter.notifyDataSetChanged();
				mMenudialog.dismiss();
			}
		});
		dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mMenudialog.dismiss();
				adapter.notifyDataSetChanged();
			}
		});
		mMenudialog.setContentView(dialogView);
		mMenudialog.setCancelable(false);
		mMenudialog.setCanceledOnTouchOutside(false);
		mMenudialog.show();
	}

	private void showAccountChoiceWindow() {
		View view = mInflater.inflate(R.layout.input_selectlist, null);
		RelativeLayout contentview = (RelativeLayout) view.findViewById(R.id.input_select_listlayout);
		ListView userlist = (ListView) view.findViewById(R.id.input_select_list);
		userlist.setDividerHeight(0);

		repairadapter = new SelectListAdapter(this, maintenancesProject);
		repairadapter.setOnItemClickListener(this);
		//adapter.setOnDelBtnClickListener(this);
		userlist.setAdapter(repairadapter);

		mSelectWindow = new PopupWindow(contentview, spinner.getMeasuredWidth(), LayoutParams.WRAP_CONTENT, true);
		mSelectWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_input_bottom_normal));
		mSelectWindow.setOutsideTouchable(true);
		mSelectWindow.setFocusable(true);
		mSelectWindow.setOnDismissListener(ApplyEquimentActivity.this);
		mSelectWindow.showAsDropDown(spinner, 0, 0);
		mSelectWindow.setHeight(200);
	}

	@Override
	public void onDismiss() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClicked(int position) {
		mSelectWindow.dismiss();
		spinner.setText(maintenancesProject.get(position).getOptionname() + "");
		option_value = maintenancesProject.get(position).getOptionvalue();
		com_id = maintenancesProject.get(position).getCom_id();
		root_id = maintenancesProject.get(position).getRoot_id();
		option_name = maintenancesProject.get(position).getOptionname();
		
	}

}
